package com.itjiange.dao.impl;

import com.itjiange.dao.UserDao;
import com.itjiange.pojo.User;
import com.itjiange.pojo.UserRegisterDto;
import com.itjiange.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

/**
 * @author ItJiange
 * @date 2023/10/16
 */
public class UserDaoImpl implements UserDao {

    /**
     * 根据用户名查询用户是否存在
     * @param userName
     * @return
     */
    @Override
    public User getUser(String userName, String userPassword) {
        // 1. 编写 SQL
        String sql = "select * from user where userName = ? and userPassword = ?";
        // 2. 执行 SQL
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        // 3. 返回结果
        try {
            return queryRunner.query(sql, new BeanHandler<User>(User.class), userName, userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insertUser(UserRegisterDto userRegisterDto) {
        // 1. 编写 SQL
        String sql = "insert into user (userName, userPassword, emailAddress, hobby) values (?, ?, ?, ?);";
        // 2. 执行 sql
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String username = userRegisterDto.getUsername();
        String userPassword = userRegisterDto.getUserPassword();
        String emailAddress = userRegisterDto.getEmailAddress();
        String hobby = userRegisterDto.getHobby();
        try {
            return queryRunner.update(sql, username, userPassword, emailAddress, hobby);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public List<User> selectAllUser() {
        String sql = "select * from user;";
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }
}
